package com.remote.client;


import com.remote.common.context.listener.ReadListener;
import com.remote.common.model.Response;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author Cool-Coding 2018/7/24
 */
@ChannelHandler.Sharable
public class ClientChannelHandler extends SimpleChannelInboundHandler<Response> {

    /**
     * logger
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(ClientChannelHandler.class);
    private final RemoteClient remoteClient;

    public ClientChannelHandler(RemoteClient remoteClient) {
        this.remoteClient = remoteClient;
    }

    @SuppressWarnings("unchecked")
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, Response request) {
        try {
            for (ReadListener responseReadListener : remoteClient.getReadListeners()) {
                responseReadListener.onRead(ctx, request);
            }
        } catch (Throwable e) {
            e.printStackTrace();
            LOGGER.error("通道读取异常" + request.toString(), e);
        }

    }


    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        LOGGER.error(cause.getMessage(), cause);
        ctx.close();
    }

}
